<template>
  <div class="recipes-page">
    <a-page-header
      title="食谱管理"
      sub-title="添加、编辑和删除食谱"
      @back="() => $router.push('/diet')"
    >
      <template #extra>
        <a-button type="primary" @click="showAddModal">
          添加食谱
        </a-button>
      </template>
    </a-page-header>

    <a-card :bordered="false" style="margin-top: 16px">
      <a-form layout="inline" :model="searchForm" @finish="handleSearch">
        <a-form-item name="keyword" label="关键词">
          <a-input
            v-model:value="searchForm.keyword"
            placeholder="食谱名称"
            allowClear
          />
        </a-form-item>
        
        <a-form-item name="suitable" label="适合糖尿病">
          <a-select
            v-model:value="searchForm.suitable"
            style="width: 120px"
            placeholder="全部"
            allowClear
          >
            <a-select-option :value="1">适合</a-select-option>
            <a-select-option :value="0">不适合</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item>
          <a-button type="primary" html-type="submit">
            搜索
          </a-button>
          <a-button style="margin-left: 8px" @click="resetSearch">
            重置
          </a-button>
        </a-form-item>
      </a-form>

      <a-table
        :columns="columns"
        :data-source="recipes"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
        style="margin-top: 16px"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'image'">
            <img
              v-if="record.image"
              :src="record.image"
              :alt="record.name"
              style="width: 50px; height: 50px; object-fit: cover;"
            />
            <span v-else>无图片</span>
          </template>
          
          <template v-if="column.key === 'suitable'">
            <a-tag :color="record.suitable === 1 ? 'green' : 'red'">
              {{ record.suitable === 1 ? '适合' : '不适合' }}
            </a-tag>
          </template>
          
          <template v-if="column.key === 'action'">
            <a-button type="link" size="small" @click="viewDetail(record)">查看</a-button>
            <a-divider type="vertical" />
            <a-button type="link" size="small" @click="showEditModal(record)">编辑</a-button>
            <a-divider type="vertical" />
            <a-popconfirm
              title="确定要删除这个食谱吗？"
              ok-text="确定"
              cancel-text="取消"
              @confirm="deleteRecipe(record.id)"
            >
              <a-button type="link" danger size="small">删除</a-button>
            </a-popconfirm>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 添加/编辑食谱的模态框 -->
    <a-modal
      :visible="modalVisible"
      :title="formMode === 'add' ? '添加食谱' : '编辑食谱'"
      @cancel="modalVisible = false"
      @ok="handleSubmit"
      :confirmLoading="submitLoading"
      width="700px"
    >
      <a-form
        :model="recipeForm"
        :rules="rules"
        ref="recipeFormRef"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item name="title" label="食谱名称">
          <a-input v-model:value="recipeForm.title" />
        </a-form-item>
        
        <a-form-item name="description" label="描述">
          <a-textarea v-model:value="recipeForm.description" :rows="3" />
        </a-form-item>
        
        <a-form-item name="image" label="图片URL">
          <a-input v-model:value="recipeForm.image" placeholder="输入图片URL" />
        </a-form-item>
        
        <a-form-item name="suitable" label="适合糖尿病">
          <a-switch v-model:checked="recipeForm.suitable" :checked-value="1" :un-checked-value="0" />
        </a-form-item>
        
        <a-form-item name="ingredients" label="食材列表">
          <div v-for="(ingredient, index) in recipeForm.ingredients" :key="index" style="display: flex; margin-bottom: 8px;">
            <a-select
              v-model:value="ingredient.foodId"
              style="width: 180px; margin-right: 8px;"
              placeholder="选择食物"
              @change="(value) => updateIngredient(index, 'foodId', value)"
            >
              <a-select-option v-for="food in foods" :key="food.id" :value="food.id">
                {{ food.name }}
              </a-select-option>
            </a-select>
            
            <a-input-number
              v-model:value="ingredient.amount"
              style="width: 100px; margin-right: 8px;"
              placeholder="数量"
              :min="0"
              @change="(value) => updateIngredient(index, 'amount', value)"
            />
            
            <a-select
              v-model:value="ingredient.unit"
              style="width: 100px; margin-right: 8px;"
              placeholder="单位"
              @change="(value) => updateIngredient(index, 'unit', value)"
            >
              <a-select-option value="g">克</a-select-option>
              <a-select-option value="ml">毫升</a-select-option>
              <a-select-option value="个">个</a-select-option>
              <a-select-option value="勺">勺</a-select-option>
            </a-select>
            
            <a-button danger @click="removeIngredient(index)" v-if="recipeForm.ingredients.length > 1">
              <DeleteOutlined />
            </a-button>
          </div>
          <a-button type="dashed" block @click="addIngredient" style="margin-top: 8px;">
            <PlusOutlined /> 添加食材
          </a-button>
        </a-form-item>
        
        <a-form-item name="steps" label="烹饪步骤">
          <div v-for="(step, index) in recipeForm.steps" :key="index" style="display: flex; margin-bottom: 8px;">
            <a-input
              v-model:value="step.content"
              style="margin-right: 8px;"
              :placeholder="`第 ${index + 1} 步`"
            />
            
            <a-button danger @click="removeStep(index)" v-if="recipeForm.steps.length > 1">
              <DeleteOutlined />
            </a-button>
          </div>
          <a-button type="dashed" block @click="addStep" style="margin-top: 8px;">
            <PlusOutlined /> 添加步骤
          </a-button>
        </a-form-item>
        
        <a-form-item name="tips" label="烹饪技巧">
          <a-textarea v-model:value="recipeForm.tips" :rows="2" />
        </a-form-item>
        
        <a-form-item name="prepTime" label="准备时间(分钟)">
          <a-input-number v-model:value="recipeForm.prepTime" :min="0" style="width: 100%" />
        </a-form-item>
        
        <a-form-item name="cookTime" label="烹饪时间(分钟)">
          <a-input-number v-model:value="recipeForm.cookTime" :min="0" style="width: 100%" />
        </a-form-item>
      </a-form>
    </a-modal>
    
    <!-- 食谱详情模态框 -->
    <a-modal
      :visible="detailVisible"
      title="食谱详情"
      @cancel="detailVisible = false"
      :footer="null"
      width="700px"
    >
      <div v-if="selectedRecipe" class="recipe-detail">
        <div class="recipe-header">
          <h2>{{ selectedRecipe.title || selectedRecipe.name }}</h2>
          <a-tag :color="selectedRecipe.suitable === 1 ? 'green' : 'red'">
            {{ selectedRecipe.suitable === 1 ? '适合糖尿病' : '不适合糖尿病' }}
          </a-tag>
        </div>
        
        <div class="recipe-image" v-if="selectedRecipe.image">
          <img :src="selectedRecipe.image" :alt="selectedRecipe.title || selectedRecipe.name" />
        </div>
        
        <div class="recipe-description">
          {{ selectedRecipe.description }}
        </div>
        
        <div class="recipe-time">
          <span>准备时间: {{ selectedRecipe.prepTime }}分钟</span>
          <span>烹饪时间: {{ selectedRecipe.cookTime }}分钟</span>
        </div>
        
        <h3>食材</h3>
        <ul class="recipe-ingredients">
          <li v-for="(ingredient, index) in selectedRecipe.ingredients" :key="index">
            {{ ingredient.foodName }} {{ ingredient.amount }} {{ ingredient.unit }}
          </li>
        </ul>
        
        <h3>烹饪步骤</h3>
        <ol class="recipe-steps">
          <li v-for="(step, index) in selectedRecipe.steps" :key="index">
            {{ step.content }}
          </li>
        </ol>
        
        <div class="recipe-tips" v-if="selectedRecipe.tips">
          <h3>烹饪技巧</h3>
          <p>{{ selectedRecipe.tips }}</p>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import axios from 'axios';
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons-vue';

export default defineComponent({
  components: {
    DeleteOutlined,
    PlusOutlined
  },
  setup() {
    const loading = ref(false);
    const submitLoading = ref(false);
    const modalVisible = ref(false);
    const detailVisible = ref(false);
    const formMode = ref('add');
    const recipeFormRef = ref(null);
    
    // 数据
    const recipes = ref([]);
    const foods = ref([]);
    const selectedRecipe = ref(null);
    
    // 分页配置
    const pagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showTotal: (total) => `共 ${total} 条记录`
    });
    
    // 搜索表单
    const searchForm = reactive({
      keyword: '',
      suitable: undefined
    });
    
    // 食谱表单
    const recipeForm = reactive({
      id: null,
      title: '',
      description: '',
      image: '',
      suitable: 1,
      prepTime: 10,
      cookTime: 20,
      tips: '',
      ingredients: [{ foodId: undefined, amount: 100, unit: 'g' }],
      steps: [{ content: '' }]
    });
    
    // 表单验证规则
    const rules = {
      title: [{ required: true, message: '请输入食谱名称' }],
      description: [{ required: true, message: '请输入食谱描述' }]
    };
    
    // 表格列定义
    const columns = [
      {
        title: 'ID',
        dataIndex: 'id',
        key: 'id',
        width: 60
      },
      {
        title: '图片',
        dataIndex: 'image',
        key: 'image',
        width: 80
      },
      {
        title: '名称',
        dataIndex: 'title',
        key: 'title',
        width: 150
      },
      {
        title: '适合糖尿病',
        dataIndex: 'suitable',
        key: 'suitable',
        width: 100
      },
      {
        title: '准备时间',
        dataIndex: 'prepTime',
        key: 'prepTime',
        width: 90,
        render: (text) => `${text}分钟`
      },
      {
        title: '烹饪时间',
        dataIndex: 'cookTime',
        key: 'cookTime',
        width: 90,
        render: (text) => `${text}分钟`
      },
      {
        title: '描述',
        dataIndex: 'description',
        key: 'description',
        ellipsis: true
      },
      {
        title: '操作',
        key: 'action',
        width: 150,
        fixed: 'right'
      }
    ];
    
    // 获取食物列表
    const fetchFoods = async () => {
      try {
        const response = await axios.get('/admin/diet/foods', {
          params: { pageSize: 1000 }
        });
        if (response.data.code === 0) {
          foods.value = response.data.data.list || [];
        }
      } catch (error) {
        console.error('获取食物列表失败', error);
        message.error('获取食物列表失败');
      }
    };
    
    // 获取食谱列表
    const fetchRecipes = async () => {
      try {
        loading.value = true;
        const params = {
          page: pagination.current,
          pageSize: pagination.pageSize,
          ...searchForm
        };
        
        // 移除undefined或null的属性
        Object.keys(params).forEach(key => {
          if (params[key] === undefined || params[key] === null) {
            delete params[key];
          }
        });
        
        const response = await axios.get('/admin/diet/recipes', { params });
        if (response.data.code === 0) {
          const data = response.data.data;
          recipes.value = data.list || [];
          pagination.total = data.total || 0;
        } else {
          message.error(response.data.msg || '获取食谱列表失败');
        }
      } catch (error) {
        console.error('获取食谱列表失败', error);
        message.error('获取食谱列表失败');
      } finally {
        loading.value = false;
      }
    };
    
    // 表格变化处理(分页、排序等)
    const handleTableChange = (pag) => {
      pagination.current = pag.current;
      pagination.pageSize = pag.pageSize;
      fetchRecipes();
    };
    
    // 搜索处理
    const handleSearch = () => {
      pagination.current = 1;
      fetchRecipes();
    };
    
    // 重置搜索
    const resetSearch = () => {
      searchForm.keyword = '';
      searchForm.suitable = undefined;
      pagination.current = 1;
      fetchRecipes();
    };
    
    // 添加食材
    const addIngredient = () => {
      recipeForm.ingredients.push({ foodId: undefined, amount: 100, unit: 'g' });
    };
    
    // 移除食材
    const removeIngredient = (index) => {
      recipeForm.ingredients.splice(index, 1);
    };
    
    // 更新食材
    const updateIngredient = (index, key, value) => {
      recipeForm.ingredients[index][key] = value;
    };
    
    // 添加步骤
    const addStep = () => {
      recipeForm.steps.push({ content: '' });
    };
    
    // 移除步骤
    const removeStep = (index) => {
      recipeForm.steps.splice(index, 1);
    };
    
    // 显示添加模态框
    const showAddModal = () => {
      formMode.value = 'add';
      // 重置表单
      recipeForm.id = null;
      recipeForm.title = '';
      recipeForm.description = '';
      recipeForm.image = '';
      recipeForm.suitable = 1;
      recipeForm.prepTime = 10;
      recipeForm.cookTime = 20;
      recipeForm.tips = '';
      recipeForm.ingredients = [{ foodId: undefined, amount: 100, unit: 'g' }];
      recipeForm.steps = [{ content: '' }];
      
      modalVisible.value = true;
    };
    
    // 显示编辑模态框
    const showEditModal = async (record) => {
      formMode.value = 'edit';
      
      try {
        loading.value = true;
        const response = await axios.get(`/admin/diet/recipes/${record.id}`);
        
        if (response.data.code === 0) {
          const data = response.data.data;
          
          // 填充表单
          recipeForm.id = data.id;
          recipeForm.title = data.title || data.name;
          recipeForm.description = data.description;
          recipeForm.image = data.image;
          recipeForm.suitable = data.suitable;
          recipeForm.prepTime = data.prepTime;
          recipeForm.cookTime = data.cookTime;
          recipeForm.tips = data.tips;
          
          // 设置食材
          if (data.ingredients && data.ingredients.length > 0) {
            recipeForm.ingredients = data.ingredients.map(item => ({
              foodId: item.foodId,
              amount: item.amount,
              unit: item.unit
            }));
          } else {
            recipeForm.ingredients = [{ foodId: undefined, amount: 100, unit: 'g' }];
          }
          
          // 设置步骤
          if (data.steps && data.steps.length > 0) {
            recipeForm.steps = data.steps.map(item => ({
              content: item.content
            }));
          } else {
            recipeForm.steps = [{ content: '' }];
          }
          
          modalVisible.value = true;
        } else {
          message.error(response.data.msg || '获取食谱详情失败');
        }
      } catch (error) {
        console.error('获取食谱详情失败', error);
        message.error('获取食谱详情失败');
      } finally {
        loading.value = false;
      }
    };
    
    // 查看详情
    const viewDetail = async (record) => {
      try {
        loading.value = true;
        const response = await axios.get(`/admin/diet/recipes/${record.id}`);
        
        if (response.data.code === 0) {
          selectedRecipe.value = response.data.data;
          detailVisible.value = true;
        } else {
          message.error(response.data.msg || '获取食谱详情失败');
        }
      } catch (error) {
        console.error('获取食谱详情失败', error);
        message.error('获取食谱详情失败');
      } finally {
        loading.value = false;
      }
    };
    
    // 提交表单
    const handleSubmit = async () => {
      try {
        await recipeFormRef.value.validate();
        
        // 验证是否选择了食物
        const hasEmptyIngredient = recipeForm.ingredients.some(item => !item.foodId);
        if (hasEmptyIngredient) {
          return message.error('请为每个食材选择具体食物');
        }
        
        // 验证步骤是否有内容
        const hasEmptyStep = recipeForm.steps.some(item => !item.content);
        if (hasEmptyStep) {
          return message.error('请完善每个烹饪步骤');
        }
        
        submitLoading.value = true;
        
        let response;
        if (formMode.value === 'add') {
          response = await axios.post('/admin/diet/recipes', recipeForm);
        } else {
          response = await axios.put(`/admin/diet/recipes/${recipeForm.id}`, recipeForm);
        }
        
        if (response.data.code === 0) {
          message.success(formMode.value === 'add' ? '添加成功' : '更新成功');
          modalVisible.value = false;
          fetchRecipes();
        } else {
          message.error(response.data.msg || (formMode.value === 'add' ? '添加失败' : '更新失败'));
        }
      } catch (error) {
        console.error(formMode.value === 'add' ? '添加失败' : '更新失败', error);
        message.error(formMode.value === 'add' ? '添加失败' : '更新失败');
      } finally {
        submitLoading.value = false;
      }
    };
    
    // 删除食谱
    const deleteRecipe = async (id) => {
      try {
        loading.value = true;
        const response = await axios.delete(`/admin/diet/recipes/${id}`);
        if (response.data.code === 0) {
          message.success('删除成功');
          fetchRecipes();
        } else {
          message.error(response.data.msg || '删除失败');
        }
      } catch (error) {
        console.error('删除失败', error);
        message.error('删除失败');
      } finally {
        loading.value = false;
      }
    };
    
    onMounted(() => {
      fetchFoods();
      fetchRecipes();
    });
    
    return {
      loading,
      submitLoading,
      modalVisible,
      detailVisible,
      formMode,
      recipeFormRef,
      recipes,
      foods,
      selectedRecipe,
      pagination,
      searchForm,
      recipeForm,
      rules,
      columns,
      handleTableChange,
      handleSearch,
      resetSearch,
      addIngredient,
      removeIngredient,
      updateIngredient,
      addStep,
      removeStep,
      showAddModal,
      showEditModal,
      viewDetail,
      handleSubmit,
      deleteRecipe
    };
  }
});
</script>

<style scoped>
.recipes-page {
  margin: 0 16px;
}

.recipe-detail {
  padding: 0 16px;
}

.recipe-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.recipe-header h2 {
  margin: 0;
  margin-right: 12px;
}

.recipe-image {
  margin-bottom: 16px;
}

.recipe-image img {
  max-width: 100%;
  max-height: 300px;
  border-radius: 4px;
}

.recipe-description {
  margin-bottom: 16px;
  color: #666;
}

.recipe-time {
  display: flex;
  margin-bottom: 16px;
}

.recipe-time span {
  margin-right: 24px;
  color: #666;
}

.recipe-ingredients {
  margin-bottom: 24px;
}

.recipe-steps {
  margin-bottom: 24px;
}

.recipe-steps li {
  margin-bottom: 8px;
}

.recipe-tips {
  background-color: #f5f5f5;
  border-radius: 4px;
  padding: 12px;
}
</style> 